import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { NzMessageService, NzModalRef, UploadFile,NzModalService } from 'ng-zorro-antd';

@Component({
  selector: 'app-takephoto',
  templateUrl: './takephoto.component.html',
  styleUrls:["./takephoto.less"]
})
export class TakephotoComponent implements OnInit,AfterViewInit {
  @ViewChild('videoElement',{ static: false }) videoElement: ElementRef;
  @ViewChild('canvasElement',{ static: false }) canvasElement: ElementRef;
  stream:any
  newVariable:any
  video:any
  canvas:any
  constructor( private modalRef: NzModalRef,private msg: NzMessageService) { }

  ngOnInit() {
    this.newVariable = window.navigator
  }
  ngAfterViewInit(): void {
    const video = this.videoElement.nativeElement
    //调用用户媒体设备, 访问摄像头
    // this.getUserMedia({ video: { width: 533, height: 432 } }, this.success, this.error);
    navigator.mediaDevices.getUserMedia({video: { width: 533, height: 432 }}).then(stream => {
      this.stream = stream
      video.srcObject = stream;
      video.play();
    }).catch(err=>{
      this.msg.warning("未发现设备！")
    })
  }
  takePhoto(){
    let context = this.canvasElement.nativeElement.getContext('2d');	
    context.drawImage(this.videoElement.nativeElement, 27,60,433,370,0,0,533,432);
    // 获取图片base64链接
    var image = this.canvasElement.nativeElement.toDataURL('image/png');
    if(this.stream){
      this.stream.getTracks()[0].stop()
      this.modalRef.close(image);
    }else{
      this.msg.warning("未打开摄像头！")
    }
  }
  //访问用户媒体设备的兼容方法
  getUserMedia(constraints, success, error) {
      if (this.newVariable.mediaDevices.getUserMedia) {
          //最新的标准API
          this.newVariable.mediaDevices.getUserMedia(constraints).then(success).catch(error);
      } else if (this.newVariable.webkitGetUserMedia) {
          //webkit核心浏览器
          this.newVariable.webkitGetUserMedia(constraints, success, error)
      } else if (this.newVariable.mozGetUserMedia) {
          //firfox浏览器
          this.newVariable.mozGetUserMedia(constraints, success, error);
      } else if (this.newVariable.getUserMedia) {
          //旧版API
          this.newVariable.getUserMedia(constraints, success, error);
      }
  }
  success(stream):void {
      // this.stream = stream
      //将视频流设置为video元素的源   
      this.video.srcObject = stream
      this.video.play()
  }
  error(error) {
      console.log(error)
  }

}
